<template>
  <div class="login-container">
    <el-card class="login-card">
      <h2 class="login-title">租车平台登录</h2>
      <el-form :model="loginForm" :rules="rules" ref="loginFormRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="loginForm.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" show-password @keyup.enter="handleLogin"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="handleLogin" style="width: 100%;">登录</el-button>
        </el-form-item>
        <div class="form-footer">
          <span>没有账号？</span>
          <router-link to="/register">立即注册</router-link>
        </div>
      </el-form>
      
      <div class="test-accounts">
        <div>测试账号：</div>
        <div>普通用户：test / 123456</div>
        <div>管理员：admin / admin123</div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store/user'

const router = useRouter()
const userStore = useUserStore()
const loginFormRef = ref(null)
const loading = ref(false)

// 表单数据
const loginForm = reactive({
  username: '',
  password: ''
})

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6个字符', trigger: 'blur' }
  ]
}

// 处理登录
const handleLogin = () => {
  loginFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    loading.value = true
    try {
      // 模拟管理员登录 - 仅用于开发测试，实际环境请删除这段代码
      if (loginForm.username === 'admin' && loginForm.password === 'admin123') {
        // 创建模拟管理员用户数据
        const adminUser = {
          id: 9999,
          username: 'admin',
          realName: '系统管理员',
          role: 'admin',
          creditScore: 100,
          status: 1,
          token: 'mock-admin-token'
        }
        
        // 直接存储到localStorage
        localStorage.setItem('token', adminUser.token)
        localStorage.setItem('userId', adminUser.id)
        localStorage.setItem('user', JSON.stringify(adminUser))
        
        // 更新store
        userStore.$patch({ 
          userInfo: adminUser,
          token: adminUser.token,
          userId: adminUser.id
        })
        
        ElMessage.success('管理员登录成功')
        router.push('/admin/dashboard')
        return
      }
      
      // 普通用户登录流程
      await userStore.login(loginForm)
      
      ElMessage.success('登录成功')
      
      // 检查用户是否是管理员，如果是则跳转到管理控制台
      if (userStore.isAdmin) {
        router.push('/admin/dashboard')
      } else {
        // 否则跳转到首页或上一个页面
        const redirect = router.currentRoute.value.query.redirect || '/'
        router.push(redirect)
      }
    } catch (error) {
      console.error('登录失败:', error)
      ElMessage.error(error.message || '登录失败，请检查用户名和密码')
    } finally {
      loading.value = false
    }
  })
}
</script>

<style scoped>
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
}

.login-card {
  width: 400px;
}

.login-title {
  text-align: center;
  margin-bottom: 20px;
  color: #409EFF;
}

.form-footer {
  margin-top: 20px;
  text-align: center;
}

.form-footer a {
  color: #409EFF;
  text-decoration: none;
  margin-left: 5px;
}

.test-accounts {
  margin-top: 20px;
  padding: 10px;
  border-top: 1px dashed #ccc;
  font-size: 12px;
  color: #666;
}
</style>